const {
  $Toast
} = require('../../dist/base/index')
export const API_URL = "http://weiyj.top/"
var header = {
  'content-type': 'application/json'
}


function fetchApi(url, params, method = 'POST',isAuth = false) {
  if(isAuth == true){
    setHeaderToken()
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: API_URL + url,
      method: method,
      data: data,
      header: header,
      success: function(res) {
        // 错误提示
        if(res.data.code == '2000'){
          $Toast({
            content: res.data.msg,
            type: 'warning'
          });
        }
        resolve(res)
      },
      fail: function(res) {
        $Toast({
          content: '程序错误',
          type: 'error'
        });
        reject(res)
      }
    })
  })
}

// 设置token验证
function setHeaderToken() {
  wx.getStorage({
    key: 'accessToken',
    success: function(res) {
      header.Authorization = 'Bearer ' + res.data
    },
    fail: function(error) {
      $Toast({
        content: '请登录...',
        type: 'error'
      });
      console.log(error)
    },
    complete: function() {
      complete && typeof complete == 'function' ? complete(header) : null // typeof 获取操作符的类型 (typeof complete) 获取complete 的类型

    }
  })
}

module.exports.getRequest = fetchApi